<!-- 聊天 -->
<template>
  <div class="chat-box">
    <recent-chat @selectedChat="handleSelectedChat"></recent-chat>
    <chat-message
      v-if="currentChat.id"
      ref="chatMessage"
      @chatRecentChange="chatRecentChange"
    ></chat-message>
  </div>
</template>

<script>
import chatMessage from "../content/message/index.vue"
import recentChat from "../sidebar/recentChat.vue"
import { mapState } from "vuex"
import { createChat, updateChat, updateReadChat } from "@/api/chat"
import { MESSAGE_TYPE } from "@/utils/constant"
export default {
  components: {
    recentChat,
    chatMessage
  },
  name: "chatPage",
  data() {
    return {
      messageKey: 1,
      currentId: null
    }
  },

  mounted() {},

  computed: {
    ...mapState({
      mqAction: (state) => state.mqttAction,
      chatId: (state) => state.chatId,
      userId: (state) => state.userInfo.userId,
      receiverId: (state) => state.receiverId,
      recentTopChatList: (state) => state.recentTopChatList,
      recentChatList: (state) => state.recentChatList,
      currentChat: (state) => state.currentChat,
      activeMenu: (state) => state.activeMenu
    }),
    isSiderChat() {
      return this.$route.path !== "/chat"
    }
  },
  created() {},

  methods: {
    async handleSelectedChat(item) {
      // this.$store.commit("setChatId", item.id)
      // this.$store.commit("setReceiverId", item.receiverId)
      // this.$store.commit("setCurrentChatInfo", item)
      // this.currentId = item.id
      this.$nextTick(() => {
        this.$refs.chatMessage.updateMessage()
      })

      // this.setMessageKeyAdd()
    },

    setMessageKeyAdd() {
      this.messageKey += 1
    },
    async chatRecentChange() {
      if (this.currentId) {
        const res = await updateReadChat({
          id: this.currentId,
          readChatIndex: this.$store.state.lastIndex,
          atMe: false
        })
        if (res) {
          this.$store.commit("updateActionChat", {
            id: this.currentId,
            atMe: false,
            unreadCount: 0
          })
        }
      }
    },
    notExisChatList(receiverId) {
      const chatList = [
        ...this.recentTopChatList,
        ...this.recentChatList
      ].filter((item) => item.isShow)
      const index = chatList.findIndex((item) => item.receiverId == receiverId)
      return index === -1
    }
  },
  watch: {
    async mqAction(action) {
      console.log("消息来了.....", action)
      const topicName = action.topic
      const reg = /im\/group\/(.+)/g
      const simpleReg = /im\/simple\/(.+)/g
      const isGroup = reg.test(topicName)
      const isPersonal = simpleReg.test(topicName)
      reg.lastIndex = 0
      simpleReg.lastIndex = 0
      if (topicName === `im/action/${this.userId}`) {
        //action.info: action: 状态， msg: 群id，userId
        switch (action.info.action) {
          case 3:
            //3 新群会话（自己）
            setTimeout(async () => {
              await this.$store.dispatch("getRecentChatList")
              this.$store.commit("updateChatList", action.info)
              this.$store.dispatch("doSubscribe", this.isSiderChat)
            }, 2000)
            break
          case 4:
            //4 退群 会话列表是否存在（自己）
            //退订mq 刷会话列表
            this.$store.dispatch("doUnSubscribe", action.info.msg)
            break
          case 5:
            //5 群公告 群名称 群成员 （群成员）
            this.$store.dispatch("getGroupList")
            this.$store.dispatch("getRecentChatList")
            break

          case 6:
            //6 @me
            this.$store.commit("updateActionChat", {
              id: action.info.msg,
              atMe:
                this.$store.state.currentChatInfo.id == action.info.msg
                  ? false
                  : true
            })
            break
          default:
            break
        }
      } else if (isGroup || isPersonal) {
        if (action.info.senderName) {
          new Notification("收到一条新消息", {
            body: action.info.senderName + "：" + action.info.contentText
          })
        }
        const id = isGroup
          ? reg.exec(topicName)[1]
          : simpleReg.exec(topicName)[1]
        //判断是否存在会话列表中,没有的话刷新会话列表（群聊一直）
        if (
          this.isSiderChat &&
          ((action.info.isGroup &&
            this.notExisChatList(action.info.receiverId)) ||
            (!action.info.isGroup &&
              this.notExisChatList(action.info.senderId)))
        ) {
          this.$store.dispatch("getRecentChatList")
          return
        }
        //如果处于当前窗口
        if (
          id == this.receiverId ||
          (action.info.senderId == this.receiverId &&
            action.info.isGroup === false)
        ) {
          this.$store.commit("setLastIndex", this.$store.state.lastIndex + 1)
          if (this.$refs.chatMessage.isExisUUId(action.info.uuid)) {
            return
          }
          this.$refs.chatMessage.receiverMessageAppend({
            ...action.info,
            status: "end"
          })
          // 对方来消息，调取已读
          if (action.info.senderId !== this.userId) {
            await updateReadChat({
              id: this.currentId,
              readChatIndex: this.$store.state.lastIndex,
              atMe: false
            })
          }
          this.$store.commit("updateChatList", {
            ...action.info,
            unreadCount: 0
          })
        } else {
          this.$store.commit("updateChatList", action.info)
        }
      }
    },
    activeMenu(val) {
      if (val === "badge") {
        const currentChatInfo = this.$store.state.currentChatInfo
        if (
          this.$store.state.isGroup ||
          (currentChatInfo && currentChatInfo.isGroup === false)
        ) {
          if (currentChatInfo) {
            this.handleSelectedChat(currentChatInfo)
          }
        } else {
          this.$store.commit("setChatId", "")
          this.$store.commit("setCurrentChatInfo", "")
          this.currentId = ""
          this.setMessageKeyAdd()
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.chat-box {
  display: flex;
  height: 100%;
}
</style>
